var http = require('http')
var createHandler = require('gitee-webhook-handler')
var handler = createHandler({ path: '/webhook', secret: '123456' })

function run_cmd(cmd, args, callback) {
  var spawn = require('child_process').spawn;
  var child = spawn(cmd, args,
  {
      stdio: ['inherit', 'pipe', 'pipe'] // 继承标准输出，但捕获标准错误  
  });
  var resp = "";
  child.stdout.on('data', function (buffer) { 
      console.log(`stdout: ${buffer}`);
      resp += buffer.toString(); 
  });
  child.stdout.on('end', function () { 
      console.log(`stdout:end `);
      callback(resp);
      
  });
  child.stdout.on('error', (err) => {  
    console.error('An error occurred while running the subprocess:', err);  
  });
}

http.createServer(function (req, res) {
  console.log('请求进入')
  handler(req, res, function (err) {
    // 检查响应头是否已经发送
    if (res.headersSent) {
      // 如果响应头已发送，不再尝试修改响应
      return;
    }
    if (err) {
      console.error('处理请求时出错:', err);
      res.statusCode = 500;
      res.end('处理请求时出错');
    } else {
      res.statusCode = 404;
      res.end('未找到该路径');
    }
  });
}).listen(9603, () => {  
  console.log('The server is running at *: 9603')  
})

handler.on('error', function (err) {
  console.error('Error:', err.message)
})
/*
测试push_hooks
进入仓库 - 项目主页 - 管理 - WebHooks
自行看日志输出
*/
handler.on('push_hooks', function (event) {
  console.log("测试 push_hooks")
  let pname = event.payload.repository.name
  console.log('Received a push event for %s to %s', pname, event.payload.ref);
  run_cmd('sh', ['./sh2.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置
})
handler.on('Push Hook', function (event) {
  console.log("正式 Push Hook")
  let pname = event.payload.repository.name
  console.log('Received a push event for %s to %s', pname, event.payload.ref);
  // pname 是项目名字，和gitee项目名称对应
  console.log(pname, '项目准备构建')
  switch (pname) {
    // VuePress
    case 'xiaoduanVuePress': 
      run_cmd('sh', ['./sh1.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置
      break;
    // vue3 + element-plus
    case 'dei-vue-admin': 
    run_cmd('sh', ['./sh2.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置
    break;
    // net
    case 'dei-net':
      run_cmd('sh', ['./sh_net.sh'], function (text) { console.log(text) });// 需要执>行的脚本位置
      break;
  }
})